# with open("hello.txt", "w") as file:
#     file.write("dddd")

"""
上下文管理器

with语句
先调用对象里的__enter__方法
结束时再调用__exit__方法

with Timer() as timer
timer得到的是__enter__方法的返回值

__exit__方法的返回值 True/False：
如果with包裹的代码出现异常, return True代表不向外抛出异常，return False代表正常向外抛出异常
"""
import time


class Timer:
    def __init__(self):
        self.elapsed = 0

    def __enter__(self):
        self.start = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end = time.perf_counter()
        self.elapsed = self.end - self.start
        # False、None 正常抛出异常 True不抛出异常
        return False
        # return None
        # return True


# 利用 上下文管理器，计算中间这段代码的运行时间
with Timer() as timer:
    nums = []
    for n in range(10000):
        nums.append(n ** 2)
    raise Exception("有问题")

print(timer.elapsed)
